﻿(function() {
    nova.widgets.BumpManager = function() {
        this.watchFrequency = 20;
        this.stopOnBumped = true;
        this.lastAcceleration = null;
        this.lastLastAcceleration = null;
        this.watchId = null;
    };
    
    nova.widgets.BumpManager.prototype = {
        start: function() {
            var obj = this;
            obj.lastAcceleration = null;
            obj.lastLastAcceleration = null;
            obj.watchId = navigator.accelerometer.watchAcceleration(function(acceleration) {
                if (obj.lastAcceleration == null) {
                    obj.lastAcceleration = acceleration;
                    return;
                }
                if (obj.lastAcceleration.timestamp == acceleration.timestamp) {
                    return;
                }
                if (obj.lastLastAcceleration != null) {
                    var dx1 = Math.abs(obj.lastAcceleration.x - obj.lastLastAcceleration.x);
                    var dy1 = Math.abs(obj.lastAcceleration.y - obj.lastLastAcceleration.y);
                    var dx2 = Math.abs(acceleration.x - obj.lastAcceleration.x);
                    var dy2 = Math.abs(acceleration.y - obj.lastAcceleration.y);
                    var dxx = Math.abs(acceleration.x - obj.lastLastAcceleration.x);
                    var dyy = Math.abs(acceleration.y - obj.lastLastAcceleration.y);
                    var bumped = ((dx1 + dx2) >= 10 && dxx < (dx1 + dx2) / 4)
                        || ((dy1 + dy2) >= 10 && dyy < (dy1 + dy2) / 4);
                    if (bumped) {
                        $(obj).trigger('onBumped');
                    }
                }
                obj.lastLastAcceleration = obj.lastAcceleration;
                obj.lastAcceleration = acceleration;
            },
                function() {
                    $(obj).trigger('onError');
                },
                {
                    frequency: obj.watchFrequency
                });
        },
        stop: function() {
            navigator.accelerometer.clearWatch(this.watchId);
        },
        onBumped: function(handler) {
            if (this.stopOnBumped) {
                this.stop();
            }
            $(this).bind('onBumped', handler);
        },
        onError: function(handler) {
            $(this).bind('onError', handler);
        }
    };
})();
